<template>
	<scroll-view scroll-y="true" id="register-index" class="container" :data-theme="themeStyle">
		<!-- <view class="iconfont iconclose back-btn" @click="$util.goBack()"></view> -->
		<view class="header-wrap">
			<view class="title">注册</view>
			<view class="regisiter-agreement">
				<text class="color-tip">已有账号,</text>
				<text class="color-base-text" @click="toLogin">立即登录</text>
			</view>
		</view>
		<view class="body-wrap">
			<view class="form-wrap" v-if="false">
				<!--  -->
				<view class="input-wrap" v-show="registerMode == 'mobile'">
					<view class="content">
						<view class="area-code">+86</view>
						<input type="number" placeholder="仅限中国大陆手机号注册" placeholder-class="input-placeholder" class="input" maxlength="11" v-model="formData.mobile" />
					</view>
				</view>
				<view class="input-wrap" v-show="registerMode == 'account'">
					<view class="content"><input type="text" placeholder="请输入账号" placeholder-class="input-placeholder" class="input" v-model="formData.account" /></view>
				</view>
				<view class="input-wrap" v-show="registerMode == 'account'">
					<view class="content"><input type="password" placeholder="请输入密码" placeholder-class="input-placeholder" class="input" v-model="formData.password" /></view>
				</view>
				<view class="input-wrap" v-show="registerMode == 'account'">
					<view class="content">
						<input type="password" placeholder="请确认密码" placeholder-class="input-placeholder" class="input" v-model="formData.rePassword" />
					</view>
				</view>
				<view class="input-wrap">
					<view class="content">
						<input type="text" placeholder="请输入验证码" placeholder-class="input-placeholder" class="input" v-model="formData.vercode" />
						<image :src="captcha.img" class="captcha" @click="getCaptcha"></image>
					</view>
				</view>
				<!-- -->
				<view class="input-wrap"  v-show="registerMode == 'mobile'">
					<view class="content">
						<input type="text" placeholder="请输入动态码" placeholder-class="input-placeholder" class="input" v-model="formData.dynacode" />
						<view class="dynacode" :class="dynacodeData.seconds == 120 ? 'color-base-text' : 'color-tip'" @click="sendMobileCode">{{ dynacodeData.codeText }}</view>
					</view>
				</view>
			</view>
			
			<!-- new布局 -->
			<view class="form-wrap">
				<view class="input-wrap" >
					<view class="content">
						<input type="text" v-model="formObj.nickname" placeholder="您的姓名" placeholder-class="input-placeholder" class="input"  />
					</view>
				</view>
				<view class="input-wrap" >
					<view class="content">
						<view class="area-code" @click="$refs.countryPopup.open()">
							<view class="h6">
								<text>{{selectObj.short}}</text>
								<text style="margin-left:12rpx;">+{{selectObj.tel}}</text>
							</view>
							<image src="/static/icon/icon_down_01.png" class="down-icon" mode=""></image>
						</view>
						<input type="number" v-model="formObj.mobile" placeholder="请输入手机号码" placeholder-class="input-placeholder" class="input" maxlength="11"  />
					</view>
				</view>
				<view class="input-wrap" >
					<view class="content">
						<input type="text" v-model="formObj.email" placeholder="请输入电子邮件地址" placeholder-class="input-placeholder" class="input"  />
					</view>
				</view>
				<view class="input-wrap" >
					<view class="content">
						<input type="password" v-model="formObj.password" placeholder="设置登录密码" maxlength="8" placeholder-class="input-placeholder" class="input"  />
					</view>
				</view>
				<view class="input-wrap" >
					<view class="content">
						<input type="password" v-model="formObj.pay_password" placeholder="设置6位纯数字交易密码" maxlength="6" placeholder-class="input-placeholder" class="input"  />
					</view>
				</view>
				<view class="input-wrap" >
					<view class="content">
						<input type="text" v-model="formObj.source_member" placeholder="邀请人ID号 (必填)" placeholder-class="input-placeholder" class="input"  />
					</view>
				</view>
				<view class="input-wrap"  >
					<view class="content">
						<input type="text" placeholder="请输入验证码" placeholder-class="input-placeholder" class="input" v-model="formObj.code" />
						<!-- @click="sendMobileCode" -->
						<view class="dynacode" :class="dynacodeData.isSend? 'color-tip' : 'color-base-text' " @click="sendCode()">{{ dynacodeData.codeText }}</view>
					</view>
				</view>
			</view>
			
			<!-- <view class="login-mode-box">
				<text @click="switchRegisterMode" v-show="registerMode == 'mobile' && registerConfig.register.indexOf('username') != -1">使用用户名注册</text>
				<text @click="switchRegisterMode" v-show="registerMode == 'account' && registerConfig.register.indexOf('mobile') != -1">使用手机号注册</text>
			</view> -->
			
			
			<!-- <view class="btn_view"><button type="primary" @click="registerFn" class="login-btn color-base-border color-base-bg">注册</button></view> -->
			<view class="btn_view"><button type="primary" @click="submitForm()" class="login-btn color-base-border color-base-bg">注册</button></view>
			<view class="regisiter-agreement">
				点击注册即代表您已同意
				<text class="color-base-text" @click="openPopup">《注册协议》</text>
			</view>
		</view>

		<view >
			<uni-popup ref="registerPopup" type="right" :maskClick="false">
				<view class="register-popup">
					<view class="shops-left" @click.stop="$refs.registerPopup.close()">
						<image  src="/static/icon/arrow_left_01.png" class="arrow-l" mode=""></image>
						<view class="shops-header-title">{{regisiterAgreement.title}}</view>
					</view>
					<view class="con">
						<scroll-view scroll-y="true" class="con"><rich-text :nodes="regisiterAgreement.content"></rich-text></scroll-view>
					</view>
				</view>
			</uni-popup>
		</view>
		
		<!-- 区号弹框 -->
		<uni-popup ref="countryPopup" type="right" :mask-click="true">
			<view class="country-popup">
				<view class="shops-header-box">
					<view class="shops-header">
						<view class="shops-left" @click.stop="$refs.countryPopup.close()">
							<image  src="/static/icon/arrow_left_01.png" class="arrow-l" mode=""></image>
							<view class="shops-header-title">选择区号</view>
						</view>
						<view class="shops-right" >
							<!-- @click="toBack('/pages/index/index/index')" -->
							<!-- <image src="/static/icon/home_icon_02.png" class="home-icon" mode=""></image>
							<view class="to-home">回到首页</view> -->
						</view>				
					</view>
				</view>
				<view class="country-ul">
					<view class="country-li" v-for="(obj,l) in countryArr" :key="l" @click.stop="selectFn(obj,l)">
						<view class="li-name">
							<text >{{obj.name}} <text class="h6">+{{obj.tel}}</text></text>
							<image v-show="selectIndex == obj.tel" src="/static/icon/icon_select_01.png" class="sel-icon" mode=""></image>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		
		

		<loading-cover ref="loadingCover"></loading-cover>
		<register-reward ref="registerReward"></register-reward>
	</scroll-view>
</template>

<script>
import uniPopup from '@/components/uni-popup/uni-popup.vue';
import validate from 'common/js/validate.js';
import registerReward from '@/components/register-reward/register-reward.vue';
import auth from 'common/js/auth.js';
import globalConfig from '@/common/js/golbalConfig.js';

export default {
	components: {
		uniPopup,
		registerReward
	},
	data() {
		return {
			allowRegister: true, // 是否允许注册
			registerMode: 'account',
			formData: {
				mobile: '',
				account: '',
				password: '',
				rePassword: '',
				vercode: '',
				dynacode: '',
				key: ''
			},
			regisiterAgreement: {
				// 注册协议
				title: '',
				content: ''
			},
			captcha: {
				// 验证码
				id: '',
				img: ''
			},
			isSub: false,
			back: '', // 返回页
			dynacodeData: {
				seconds: 60,
				timer: null,
				codeText: '获取验证码',
				isSend: false
			},
			registerConfig: {
				register: ''
			},
			formObj: {
				mobile: '', // 手机号
				password: '', // 密码
				nickname: '', // 姓名 
				email: '',  // 邮箱
				source_member: '', //邀请人uid
				pay_password: '', // 支付密码
				code: '', // 验证码
				phone_code: '86',
				key: '',
			},
			countryArr: [],
			selectIndex: 86,
			selectObj: {
				short: 'CN',
				tel: 86
			},
		};
	},
	mixins: [auth, globalConfig],
	onLoad(option) {
		if (option.back) this.back = option.back;
		if(option.uid) this.formObj.source_member = option.uid;
		this.getCaptcha();
		this.getRegisiterAggrement();

		if (uni.getStorageSync('authInfo')) {
			this.authInfo = uni.getStorageSync('authInfo');
		}
		
		this.getCountry();
	},
	onShow() {
		// 刷新多语言
		this.$langConfig.refresh();
		// #ifdef MP
		this.getCode();
		// #endif
	},
	async onReady() {
		await this.getRegisterConfig();
		if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
	},
	methods: {
		// 获取区号
		getCountry(){
			this.$api.sendRequest({
				url: '/api/register/countrylist',
				method: 'get',
				success:res=>{
					if(res.code == 0){
						this.countryArr = res.data;
						// this.
						// console.log(this.countryArr.length)
					}
				}
			})
		},
		// 选择区号
		selectFn(obj,index){
			this.selectObj = obj;
			this.selectIndex = obj.tel;
			this.formObj.phone_code = obj.tel;
			this.$refs.countryPopup.close()
		},
		// 检验
		handleCheck(){
			if(!this.formObj.nickname){
				return this.$util.showToast({title: '请输入用户名'})
			}
			if(!this.formObj.mobile){
				return this.$util.showToast({title: '请输入手机号'})
			}
			if(!this.formObj.email){
				return this.$util.showToast({title: '请输入邮箱'})
			}
			if(!this.formObj.email.includes('@')){
				return this.$util.showToast({title: '请输入正确的邮箱'})
			}
			if(!this.formObj.password){
				return this.$util.showToast({title: '请输入密码'})
			}
			let regNumber = /^\+?[1-9][0-9]*$/; // 正整数
			if(!this.formObj.pay_password){
				return this.$util.showToast({title: '请输入交易密码'})
			}
			if(!regNumber.test(this.formObj.pay_password)){
				return this.$util.showToast({title: '请输入6位纯数字交易密码'})
			}
			if(!this.formObj.source_member){
				return this.$util.showToast({title: '请输入邀请人ID号'})
			}
			if(!this.formObj.code){
				return this.$util.showToast({title: '请输入验证码'})
			}
			return true;
		},
		// 提交注册
		submitForm(){
			if(this.handleCheck() !== true){
				return false;
			}
			uni.showLoading({
				mask: true,
				title:'Loading...'
			})
			console.log(JSON.stringify(this.formObj))
			this.$api.sendRequest({
				url: '/api/register/register',
				data: this.formObj,
				method: 'post',
				success: res=>{
					uni.hideLoading()
					if(res.code == 0){
						uni.removeStorageSync('loginLock');
						uni.removeStorageSync('unbound');
						uni.removeStorageSync('authInfo');
						uni.setStorageSync('token',res.data.token);
						this.$util.showToast({title: '注册成功'})
						setTimeout(()=>{
							let url = this.back ? decodeURIComponent(this.back) : '/pages/member/index/index'
							uni.reLaunch({
								url: url,
							})									
						},1500)
					}else {
						this.$util.showToast({title: res.message})
					}
				},
				fail:err=>{
					uni.hideLoading()
				}
			})
		},
		// 发送验证码
		sendCode(){
			if(!this.formObj.mobile){
				return this.$util.showToast({title: '请输入手机号'})
			}
			if(this.dynacodeData.isSend) return;
			this.$api.sendRequest({
				url: '/api/register/mobileCode',
				data: {
					mobile: this.formObj.mobile,
				},
				method: 'get',
				success: res=>{
					if(res.code == 0){
						this.$util.showToast({title: '发送验证码成功'})
						this.formObj.key = res.data.key;
						this.handleTime();
					}else {
						this.$util.showToast({title: res.message})
					}
				}
			})
		},
		// 倒计时
		handleTime(){
			this.dynacodeData.isSend = true;
			this.dynacodeData.codeText = `${this.dynacodeData.seconds}后重新获取`
			this.dynacodeData.timer = setInterval(()=>{
				if(this.dynacodeData.seconds == 0){
					this.dynacodeData.codeText = '重新获取'
					this.dynacodeData.isSend = false;
					this.dynacodeData.seconds = 60;
					clearInterval(this.dynacodeData.timer)
					return false;
				}
				this.dynacodeData.seconds--;
				this.dynacodeData.codeText = `${this.dynacodeData.seconds}后重新获取`
			},1000)
		},
		
		/**
		 * 切换注册方式
		 */
		switchRegisterMode() {
			this.registerMode = this.registerMode == 'mobile' ? 'account' : 'mobile';
		},
		/**
		 * 展示注册协议
		 */
		openPopup() {
			this.$refs.registerPopup.open();
		},
		/**
		 * 点击关闭协议
		 */
		toClose() {
			this.$refs.registerPopup.close();
		},
		/**
		 * 获取注册协议
		 */
		getRegisiterAggrement() {
			this.$api.sendRequest({
				url: '/api/register/aggrement',
				success: res => {
					if (res.code >= 0) {
						this.regisiterAgreement = res.data;
					}
				}
			});
		},
		/**
		 * 获取注册配置
		 */
		async getRegisterConfig() {
			let res = await this.$api.sendRequest({
				url: '/api/register/config',
				async: false
				});
				this.registerConfig = res.data.value;
				if (this.registerConfig.register == '') {
					this.$util.showToast({ title: '平台未启用注册!' });
					setTimeout(() => {
						this.$util.redirectTo('/pages/index/index/index', {}, 'tabbar');
					}, 1000);
				} else if (this.registerConfig.register.indexOf('username') != -1) {
					this.registerMode = 'account';
				} else {
					this.registerMode = 'mobile';
				}
				if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
		},
		/**
		 * 获取验证码
		 */
		getCaptcha() {
			this.$api.sendRequest({
				url: '/api/captcha/captcha',
				data: {
					captcha_id: this.captcha.id
				},
				success: res => {
					if (res.code >= 0) {
						this.captcha = res.data;
						this.captcha.img = this.captcha.img.replace(/\r\n/g, '');
					}
				}
			});
		},
		/**
		 * 注册
		 */
		registerFn() {
			if (this.registerMode == 'account') {
				var url = '/api/register/username';
				data = {
					username: this.formData.account,
					password: this.formData.password
				};
			} else {
				var url = '/api/register/mobile',
					data = {
						mobile: this.formData.mobile,
						key: this.formData.key,
						code: this.formData.dynacode
					};
			}
			if (this.captcha.id != '') {
				data.captcha_id = this.captcha.id;
				data.captcha_code = this.formData.vercode;
			}
			if (Object.keys(this.authInfo).length) {
				Object.assign(data, this.authInfo);
			}
			if (this.authInfo.avatarUrl) data.headimg = this.authInfo.avatarUrl;
			if (this.authInfo.nickName) data.nickname = this.authInfo.nickName;
			if (uni.getStorageSync('source_member')) data.source_member = uni.getStorageSync('source_member');

			if (this.verify(data)) {
				if (this.isSub) return;
				this.isSub = true;
				uni.showLoading({
					title: 'Loading...',
					mask: true,
				})
				this.$api.sendRequest({
					url,
					data,
					success: res => {
						uni.hideLoading()
						if (res.code >= 0) {
							var that = this;
							uni.setStorage({
								key: 'token',
								data: res.data.token,
								success: () => {
									uni.removeStorageSync('loginLock');
									uni.removeStorageSync('unbound');
									uni.removeStorageSync('authInfo');
									console.log('到这里了吗?????????')
									that.$util.showToast({
										title: '注册成功'
									});
									setTimeout(()=>{
										if (that.$refs.registerReward.getReward()) {
											that.$refs.registerReward.open();
										} else {
											let url = that.back ? decodeURIComponent(that.back) : '/pages/member/index/index'
											uni.reLaunch({
												url: url,
											})
										}										
									},1500)
								}
							});
						} else {
							this.isSub = false;
							this.getCaptcha();
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: res => {
						this.isSub = false;
						this.getCaptcha();
					}
				});
			}
		},
		
		verify(data) {
			// 手机号注册
			if (this.registerMode == 'mobile') {
				var rule = [{ name: 'mobile', checkType: 'required', errorMsg: '请输入手机号' }, { name: 'mobile', checkType: 'phoneno', errorMsg: '请输入正确的手机号' }];
				if (this.captcha.id != '') rule.push({ name: 'captcha_code', checkType: 'required', errorMsg: this.$lang('captchaPlaceholder') });
				rule.push({ name: 'code', checkType: 'required', errorMsg: this.$lang('dynacodePlaceholder') });
			}

			// 用户名注册
			if (this.registerMode == 'account') {
				var rule = [{ name: 'username', checkType: 'required', errorMsg: '请输入账号' }, { name: 'password', checkType: 'required', errorMsg: '请输入密码' }],
					regConfig = this.registerConfig;

				if (regConfig.pwd_len > 0) {
					rule.push({
						name: 'password',
						checkType: 'lengthMin',
						checkRule: regConfig.pwd_len,
						errorMsg: '密码长度不能小于' + regConfig.pwd_len + '位'
					});
				}
				if (regConfig.pwd_complexity != '') {
					let passwordErrorMsg = '密码需包含',
						reg = '';
					if (regConfig.pwd_complexity.indexOf('number') != -1) {
						reg += '(?=.*?[0-9])';
						passwordErrorMsg += '数字';
					}
					if (regConfig.pwd_complexity.indexOf('letter') != -1) {
						reg += '(?=.*?[a-z])';
						passwordErrorMsg += '、小写字母';
					}
					if (regConfig.pwd_complexity.indexOf('upper_case') != -1) {
						reg += '(?=.*?[A-Z])';
						passwordErrorMsg += '、大写字母';
					}
					if (regConfig.pwd_complexity.indexOf('symbol') != -1) {
						reg += '(?=.*?[#?!@$%^&*-])';
						passwordErrorMsg += '、特殊字符';
					}
					rule.push({
						name: 'password',
						checkType: 'reg',
						checkRule: reg,
						errorMsg: passwordErrorMsg
					});
				}
				if (this.formData.password != this.formData.rePassword) {
					this.$util.showToast({
						title: '两次密码不一致'
					});
					return false;
				}
				if (this.captcha.id != '') rule.push({ name: 'captcha_code', checkType: 'required', errorMsg: this.$lang('captchaPlaceholder') });
			}
			var checkRes = validate.check(data, rule);
			if (checkRes) {
				return true;
			} else {
				this.$util.showToast({
					title: validate.error
				});
				return false;
			}
		},
		/**
		 * 去登录
		 */
		toLogin() {
			if (this.back)
				this.$util.redirectTo('/pages/login/login/login', {
					back: this.back
				});
			else this.$util.redirectTo('/pages/login/login/login');
		},
		/**
		 * 发送手机动态码
		 */
		sendMobileCode() {
			if (this.dynacodeData.seconds != 120) return;
			var data = {
				mobile: this.formObj.mobile,
				captcha_id: this.captcha.id,
				captcha_code: ''
			};
			var rule = [
				{ name: 'mobile', checkType: 'required', errorMsg: '请输入手机号' },
				{ name: 'mobile', checkType: 'phoneno', errorMsg: '请输入正确的手机号' },
				{ name: 'captcha_code', checkType: 'required', errorMsg: '请输入验证码' }
			];
			var checkRes = validate.check(data, rule);
			if (!checkRes) {
				this.$util.showToast({ title: validate.error });
				return;
			}
			if (this.dynacodeData.isSend) return;
			this.dynacodeData.isSend = true;
			this.$api.sendRequest({
				url: '/api/register/mobileCode',
				data: data,
				success: res => {
					this.dynacodeData.isSend = false;
					if (res.code >= 0) {
						this.formData.key = res.data.key;

						if (this.dynacodeData.seconds == 120 && this.dynacodeData.timer == null) {
							this.dynacodeData.timer = setInterval(() => {
								this.dynacodeData.seconds--;
								this.dynacodeData.codeText = this.dynacodeData.seconds + 's后可重新获取';
							}, 1000);
						}
					} else {
						this.$util.showToast({ title: res.message });
					}
				},
				fail: () => {
					this.$util.showToast({ title: 'request:fail' });
					this.dynacodeData.isSend = false;
				}
			});
		}
	},
	// watch: {
	// 	'dynacodeData.seconds': {
	// 		handler(newValue, oldValue) {
	// 			if (newValue == 0) {
	// 				clearInterval(this.dynacodeData.timer);
	// 				this.dynacodeData = {
	// 					seconds: 120,
	// 					timer: null,
	// 					codeText: '获取动态码',
	// 					isSend: false
	// 				};
	// 			}
	// 		},
	// 		immediate: true,
	// 		deep: true
	// 	}
	// }
};
</script>

<style lang="scss">
@import '../public/css/common.scss';
	
</style>
<style scoped lang="scss">
/deep/ .reward-popup .uni-popup__wrapper-box {
	background: none !important;
	max-width: unset !important;
	max-height: unset !important;
}

	.header-wrap {
		margin-top: 80rpx;
	}
	.body-wrap {
		.form-wrap {
			width: 86%;
			.input-wrap {
				.content {
					.area-code {
						display: flex;
						align-items: center;
						.h6 {
							font-size: 28rpx;
							color: #303133;
						}
						.down-icon {
							width: 24rpx;
							height: 24rpx;
							display: block;
							margin-left: 12rpx;
						}
					}
				}
			}
		}	
	}


	.country-popup {
		width: 100%;
		background: #F8F7FC;
		
		// height: auto;
		overflow: auto;
		.shops-header-box {
			width: 100%;
			height: 88rpx;
			background: #fff;
			padding: 0px 32rpx;
			box-sizing: border-box;
			margin-bottom: 8rpx;
			.shops-header {
				width: 100%;
				height: 88rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.shops-left {
					display: flex;
					align-items: center;
					.shops-header-title {
						font-size: 36rpx;
						font-family: PingFangSC-Semibold, PingFang SC;
						font-weight: 600;
						color: #292929;
						line-height: 50rpx;
						margin-left: 6rpx;
					}
				}
				.shops-right {
					display: flex;
					align-items: center;
					.home-icon {
						width: 32rpx;
						height: 32rpx;
						margin-right: 12rpx;
					}
					.to-home {
						font-size: 26rpx;
						color: #31bb6d;
					}
				}
			}	
		}
		.country-ul {
			height: 100vh;
			// padding-top: 100rpx;
			overflow: auto;
			.country-li {
				width: 100%;
				background: #fff;
				padding: 0px 32rpx;
				box-sizing: border-box;
				.li-name {
					width: 100%;
					height: 110rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 2rpx solid #E8EDF5;
					text {
						font-size: 32rpx;
						color: #353535;
						.h6 {
							margin-left: 15rpx;
							color: #92969E;
						}
					}
					.sel-icon {
						width: 36rpx;
						height: 36rpx;
					}
				}
			}
		}
	}
	
	.register-popup {
		width: 100%;
		height: 100vh;
		overflow: auto;
		padding: 30rpx 34rpx;
		box-sizing: border-box;
		overflow: auto;
		.shops-left {
			display: flex;
			align-items: center;
			margin-bottom: 40rpx;
			.shops-header-title {
				font-size: 36rpx;
				font-family: PingFangSC-Semibold, PingFang SC;
				font-weight: 600;
				color: #292929;
				line-height: 50rpx;
				margin-left: 6rpx;
			}
		}
	}


</style>
